$(function () {
  // http://124.223.14.236:8060/
  const showId = localStorage.getItem('showId')
  const Id = localStorage.getItem('id')

  // 1.侧边 热门文章
  recommendList()
  function recommendList() {
    $.ajax({
      url: '/index/recommend',
      method: 'GET',
      success: function ({ errno, errmsg, data }) {
        // console.log("data", data)
        if (errno !== 0) return layer.msg(errmsg)
        //5.2-2 侧边--热门文章渲染 
        $('.items-02').append(
          data.list.map(item => {
            return `
            <li>
            <a target="_blank" href="javascript:;">
              <span class="thumbnail">
                <img src="http://124.223.14.236:8060/${item.pic}" class="thumb" />
              </span>
              <span class="text">${item.title}</span>            
            </a>
          </li>       
            `
          }).join('')
        )

      }
    })

  }

  // 2.全局数据渲染（nav区域、广告位、热门标签、友情链接、版权）
  allInfo()
  function allInfo() {
    $.ajax({
      method: 'GET',
      url: '/index/index',
      success: function ({ errno, errmsg, data }) {
        console.log("data", data)
        if (errno !== 0) return layer.msg(errmsg)
        const { allCate, allLink, allTag, banner, config, showBanner, sideBanner } = data
        // nav 头部导航区域 allCate  渲染
        // 处理无效数据
        const regCN = /[\u4e00-\u9fa5]/g
        const dealCate = allCate.filter(item => {
          return item.id >= 1 && item.id <= 10
        })
        const allCateTpl = dealCate.map(item => {
          return `
          <li class="menu-item menu-item-type-taxonomy menu-item-object-category"><a href="javascript:;" data-id = '${item.id}'><span
          class="fa ${item.icon}"></span>${item.catename.match(regCN) && item.catename !== '' ? item.catename.match(regCN).join('') : item.catename}</a></li>
          `
        }).join('')
        $('.nav').append(allCateTpl)
        $(`.header .container .nav [data-id=${Id}]`).parent('li').addClass('current_page_item')


        //  右侧广告位  sideBanner
        $('#sideBanner').html(`
        ${sideBanner.map(item => {
          const { advimgdesc, advimglink, advimgsrc, id } = item
          return ` <a href="${advimglink}" rel="nofollow" target="_blank" title="${advimgdesc}">
          <img class="g430" style="width:360px;height:133px;" src="http://124.223.14.236:8060/${advimgsrc}" alt="${advimgdesc}">
        </a>`
        }).join('')}
        `)
        //  渲染文章正文之前的广告位
        const [{ advimgdesc, advimglink, advimgsrc, id }] = showBanner
        $('#ad').html(`
         <center>
             <a href="${showBanner[0].advimglink}" title="${showBanner[0].advimgdesc}" target="_blank" rel="nofollow">
               <img src="http://124.223.14.236:8060/${showBanner[0].advimgsrc}" style="width: 728px;height:90px;" alt="">
             </a>
           </center>`)
        // 文章正文之后的广告位 showBanner
        $('#bottomAd').html(`
        <center>
            <a href="${showBanner[1].advimglink}" rel="nofollow" title="${showBanner[1].advimgdesc}" target="_blank">
              <img src="http://124.223.14.236:8060/${showBanner[1].advimgsrc}" style="width: 728px;height:90px;" alt="">
            </a>
          </center>
        `)

        // 右侧--热门标签区域内容渲染
        const reg = /[\u4E00-\u9FA5]/
        const tags = allTag.filter(function (item) {
          // console.log(reg.test(itemtagname))
          return reg.test(item.tagname) === true
        })
        // console.log("tags", tags)
        $('.widget_tags_inner').html(
          tags.map(item => {
            return `
            <li><a title="" href="javascript:;">${item.tagname}</a></li>
            `
          }).join('')
        )

        //右侧---友情链接区域
        const friendLink = allLink.filter(function (item) {
          return item.default_data === '1' && item.type === '2'
        })
        $('#allLink').html(
          friendLink.map(item => {
            return `
          <li>
          <a href="${item.url}"><img src="http://124.223.14.236:8060/${item.img}" alt="">
            <p>${item.title}</p>
          </a>
        </li>
          `
          }).join('')
        )

        //  // 版权部分 -上
        // 处理有效数据
        const newLink = allLink.filter(function (item) {
          return item.default_data === '1' && item.type === '1'
        })
        // console.log(newLink)

        $('.footer .link').append(
          newLink.map(item => {
            return `
              <a href="${item.url}" title="${item.des}">${item.des}</a> <span>|</span>
            `
          }).join('')
        )
        // 版权----下
        // 处理数据 id53,54,55
        const copyArr = config.allData.filter(item => {
          return item.id >= 53 && item.id <= 55
        })
        $('#copy').html(`
        &copy; 2021 <a href="http://blog.weknow.cn">${copyArr[1].attr_value},</a>
        &nbsp;&nbsp;联系邮箱：${copyArr[2].attr_value}
        &nbsp;&nbsp; <a href="">${copyArr[0].attr_value}</a> 
        `
        )
      }

    })
  }

  // 3.右侧-最新推荐
  hotList()
  function hotList() {
    $.ajax({
      url: '/index/hot',
      method: 'GET',
      success: function ({ errno, errmsg, data }) {
        // console.log(data);
        if (errno) return layer.msg(errmsg)
        const { list } = data
        $('.hotrecommand').html(
          list.map(({ catename, id, lovenum, pic, title }) => {
            return `
            <li class="item"><a target="_blank" href=""><img src="http://124.223.14.236:8060/${pic}"
            class="thumb" />${title}</a></li>`
          }).join('')
        )
        $('.items-01').html(
          list.map(({ catename, id, lovenum, pic, title }) => {
            return `
            <li>
            <a target="_blank" href="javascript:;">
              <span class="thumbnail">
                <img class="thumb" src="http://124.223.14.236:8060/${pic}" />
              </span>
              <span class="text">${title}</span>
              <span class="text-muted post-views">阅读(${lovenum === null ? 0 : lovenum})</span>
            </a>
          </li>`
          }).join('')
        )
      }
    })

  }

  // 4.获取本地存储的id 根据id渲染对应的文章详情页
  // const showId = localStorage.getItem('showId')
  // console.log("showId", showId)


  // 5.左侧 文章详情数据 区域
  let q = {
    id: showId
  }
  const regCN = /[\u4e00-\u9fa5]/g
  newList()
  function newList() {
    $.ajax({
      method: 'GET',
      url: '/index/show',
      data: q,
      success: function (res) {
        // 点赞变量
        let lovenum = 0
        console.log(res);


        const { errno, errmsg, data } = res
        if (errno) return layer.msg(errmsg)
        const { info, next, prev, recommend } = data
        lovenum = info.lovenum ? info.lovenum : 0


        let isCollect = info.isCollect
        // console.log(isCollect);

        // 主要内容
        const { author, cateid, catename, click, content, create_date, default_data, decription, id, isLike, pic, title, user_id, tags } = info


        let picIMG = null

        if (!pic || !pic.startsWith('upload')) {
          $('.article-content .img').hide()
        } else if (pic.startsWith('upload')) {
          picIMG = "http://124.223.14.236:8060/" + pic
        }

        // 面包屑
        $('.breadcrumbs .text-fenlei').html(catename)
        // 标题 
        $('.article-header .article-title a').html(title)
        // 标题描述
        $('.article-header .article-meta .author').html(`<a href="">${author}</a> 发布于 ${new Date(create_date).toLocaleDateString().replace(/\//g, '-')}`)
        $('.article-header .article-meta .cate-lei').html(`分类：<a href="./list.html?${id}" rel="category tag">${catename}</a>`)
        $('.article-header .article-meta .post-views').html(`阅读(${click})`)

        // 文章正文
        $('.article-content').html(`
            <p> ${content}</p>
            <img src=${picIMG} alt="" class="img">
            <p class="post-copyright">未经允许不得转载：
              <a href="">优点达资讯</a> &raquo; <a href="">${title}</a>
            </p>`)

        // 上一篇
        if (prev.length !== 0) {
          const [{ title: prevTitle, id: prevId }] = prev
          $('.article-nav .article-nav-prev').append(`<a href="./show.html?${prevId}" rel="prev">${prevTitle}</a>`)
        } else {
          $('.article-nav .article-nav-prev').append(`<a href="javascript:;" rel="prev">当前位置：起始页</a>`)
        }
        // 下一篇
        if (next.length !== 0) {
          const [{ title: nextTitle, id: nextId }] = next
          $('.article-nav .article-nav-next').append(`<a href="./show.html?${nextId}" rel="next">${nextTitle}</a>`)
        } else {
          $('.article-nav .article-nav-next').append(`<a href="javascript:;" rel="next">当前是最后一篇，无更多内容了</a>`)
        }

        // 标签信息
        if (!tags) $('.article-tags').hide()
        $('.article-tags a').html(`${tags}`)

        // 收藏
        if (isCollect) {
          $('.article-collect').addClass('collect_active')
        } else {
          $('.article-collect').removeClass('collect_active')
        }
        // 点击收藏
        $('.article-collect').on('click', function () {

          if (!isCollect) {
            isCollect = true
            $.ajax({
              url: '/user/userDataHandle',
              method: 'GET',
              data: {
                type: 1,
                article_id: showId,
                action: "add",
              },
              headers: {
                token: localStorage.getItem('Atoken') || '',
              },
              success: function (res) {
                console.log(res);
                if (res.errno) return layer.msg(res.errmsg)
                layer.msg('收藏成功', { icon: 1 })
                $('.article-collect').html('已收藏')
                $('.article-collect').toggleClass('collect_active')

              }
            })
          } else {
            isCollect = false

            $.ajax({
              url: '/user/userDataHandle',
              method: 'GET',
              data: {
                type: 1,
                article_id: showId,
                action: "del",

              },
              headers: {
                token: localStorage.getItem('Atoken') || '',
              },
              success: function (res) {
                console.log(res);
                if (res.errno) return layer.msg(res.errmsg)
                layer.msg('取消收藏', { icon: 1 })
                $('.article-collect').html('点击收藏')
                $('.article-collect').toggleClass('collect_active')

              }
            })
          }

        })

        // 相关推荐
        const reStr = recommend.map(item => {
          const { cateid, catename, id, pic, title } = item
          return `
        <li>
          <a target="_blank" href="./show.html?${id}">
            <span>
              <img src=${pic.startsWith('upload') ? "http://124.223.14.236:8060/" + pic : './static/images/default.png'} class="thumb" />
            </span>
            ${title}
          </a>
        </li>`
        }).join('')
        $('.relates-model-thumb ul').html(reStr)



        // 点赞渲染
        $('.article-social .action span').html(`${lovenum ? lovenum : 0}`)

        // 点赞或取消
        $('.article-social .action').on('click', function () {

          if ($('.action').hasClass('action-like')) {
            lovenum = +lovenum - 1
            console.log(lovenum);
            $.ajax({
              url: '/user/userDataHandle',
              method: 'GET',
              data: {
                type: 2,
                article_id: showId,
                action: "del",

              },
              headers: {
                token: localStorage.getItem('Atoken') || '',

              },
              success: function (res) {
                console.log(res);
                if (res.errno) return layer.msg(res.errmsg)
                layer.msg('取消点赞', { icon: 1 })
                $('.action').html(`点赞(${lovenum})`)
                $('.action').toggleClass('action-like')

              }
            })
          } else {
            lovenum = +lovenum + 1
            console.log(lovenum);


            $.ajax({
              url: '/user/userDataHandle',
              method: 'GET',
              data: {
                type: 2,
                article_id: showId,
                action: "add",

              },
              headers: {
                token: localStorage.getItem('Atoken') || '',
                // "Content-Type": "text/plain"
              },
              // contentType: 'application/json',
              // dataType: 'json',
              success: function (res) {
                console.log(res);
                if (res.errno) return layer.msg(res.errmsg)
                layer.msg('点赞成功', { icon: 1 })
                $('.action').html(`已赞(${lovenum})`)
                $('.action').toggleClass('action-like')

              }
            })
          }
        })
      }
      /*   success: function (res) {
          if (res.errno) return layer.msg(res.errmsg)
          const { prev, next, info, recommend } = res.data
          console.log("文章详情页", res.data)
          // 5.1渲染 面包屑--当前位置：
          $('.article-header').html(`
          <div class="breadcrumbs">
          <span class="text-muted">当前位置：</span>
          <a href="./index.html">优点达资讯系统</a>
          <small>></small>
          <a href="./list.html" class="catename">${info.catename.match(regCN).join('')}</a> <small>></small>
          <span class="text-muted">正文</span>
          </div>
          <h1 class="article-title"><a href="">${info.title}</a></h1>
          <ul class="article-meta">
          <li><a href="">${info.author}</a> 发布于 ${new Date(info.create_date).toLocaleDateString().replace(/\//g, '-')}</li>
          <li>分类：<a href="./list.html" rel="category tag" class="catename">${info.catename.match(regCN).join('')}</a></li>
          <li><span class="post-views">阅读(${info.click})</span></li>
          <li><a class ="collect" data-id="1" href="javascript:;">点击收藏</a></li>
        </ul>
            `)
  
  
          // 5.2 渲染文章内容
          $('.article-content').html(`
            <p>${info.content}</p>
          <p class="post-copyright">未经允许不得转载：
          <a href="">优点达资讯</a> &raquo; <a href="./index.html">${info.title}</a>
        </p>
            `)
  
          // 5.3 点赞
          $('.article-social').html(`<a href="javascript:;" class="action action-like" data-id="2">
            <i class="glyphicon glyphicon-thumbs-up"></i>赞 (<span>${info.lovenum ? info.lovenum : 0}</span>)
          </a>`)
  
  
          // 5.4 标签信息
          $('.article-tags').html(`标签：<a href="" rel="tag">${info.tags !== null && info.tags.match(regCN) ? info.tags.match(regCN).join('') : '德国'}</a>`)
  
          // 5.5  上下一篇
          $('.article-nav').html(`<span class="article-nav-prev">
            <span>上一篇</span>
            <a href="" rel="prev">${prev[0].title}</a>
          </span>
          <span class="article-nav-next">
            <span>下一篇</span>
            <a href="" rel="next">${next[0].title}</a>
          </span>`)
  
          // 5.6 相关推荐
          $('#recommend').html(recommend.map(item => {
            return `
            <li>
                <a target="_blank" href="javascript:;">
                  <span>
                    <img src="http://124.223.14.236:8060/${item.pic}" class="thumb" />
                  </span>
                  ${item.title}
                </a>
              </li>`
          }).join(''))
        } */
    })

  }

  // 6.nav头部导航注册点击事件  获取每个分类对应的id并进行本地存储
  $('.header .nav').on('click', 'a', function (e) {
    const id1 = $(this).attr('data-id')
    console.log("id1", id1)
    localStorage.setItem('id', id1)
    location.href = "./list.html"
    // window.history.back(-1);
  })
  // 7.点击当前位置的分类或者正文标题下的分类 能跳转到list对应法分类的页面
  $('.article-header').on('click', 'a.catename', function () {
    // window.history.back(-1);
    location.href = "./list.html"
  })

  // 分页器  laypage
  function renderLayPage(total) {
    const laypage = layui.laypage
    //执行一个laypage实例
    laypage.render({
      elem: 'laypage_box', //注意，这里的 laypage_box 是html的分页容器ID名称，不用加 # 号
      count: total, //数据总数，从服务端得到
      limit: q.limit,  //每页显示的条数。laypage将会借助 count 和 limit 计算出分页数。默认值为10
      curr: q.page,//获取起始页
      layout: ['prev', 'page', 'next', 'count', 'skip'],
      // last: '',
      theme: '#ff5e52',
      // 自定义排版。可选值有：count（总条目输区域）、prev（上一页区域）、page（分页区域）、next（下一页区域）、limit（条目选项区域）、refresh（页面刷新区域。注意：layui 2.3.0 新增） 、skip（快捷跳页区域）
      // limits: [1, 2, 3, 4, 5], //每页条数的选择项。如果 layout 参数开启了 limit，则会出现每页条数的select选择框
      jump: function (obj, first) {
        //当分页被切换时触发，函数返回两个参数：obj（当前分页的所有选项值）、first（是否首次，一般用于初始加载的判断）
        q.page = obj.curr  //更新查询的参数对象q的页码值
        q.limit = obj.limit
        // console.log(first);  //首次渲染结果为true，人为切换后 结果为undefined
        //首次不执行
        if (!first) {
          //do something
          newList()
        }
      }

    });

  }

  // 6.文章收藏 点赞功能
  function render(index) {
    $.ajax({
      url: '/user/userDataHandle',
      method: 'GET',
      data: {
        type: index,
        article_id: showId,
        action: 'add',
      },
      headers: {
        'token': localStorage.getItem('Atoken') || ''
      },
      success: function (res) {
        console.log(res);
      }
    })
  }
  //收藏
  $('.article-header').on('click', '.collect', function () {
    const index = $(this).data('id')
    // console.log("index", index)
    // console.log(localStorage.getItem('Atoken'))
    render(index)
  })
  //点赞
  $('.article-social').on('click', '.action-like', function () {
    const index = $(this).data('id')
    console.log("index", index)
    // console.log(localStorage.getItem('Atoken'))
    render(index)
  })



  // 7登录注册部分
  const token = localStorage.getItem('Atoken')
  // const token = localStorage.getItem('YOUDIANDA_TOKEN')
  console.log('token', token)

  if (token === '') {
    layer.msg('请先登录')
    return $('.slinks').html(`< a href=" "><i class="fa fa-hand-o-right"></i>&nbsp;登录</ a> |
  <a href="reg.html"><i class="fa fa-registered"></i>&nbsp;注册</ a>`)
  } else {
    $.ajax({
      method: 'POST',
      url: '/user/getUserInfo',
      headers: {
        token: token
      },
      success: function (res) {
        console.log(res);
        const user = res.data.userInfo.username || res.data.userInfo.mobile
        $('.slinks').html(`<a data-v-697ed175="" href="#/user" class="router-link-exact-active router-link-active" aria-current="page">
  <i data-v-697ed175="" class="fa fa-user"></i>&nbsp; 您好${user}，</ a>
   <a data-v-697ed175="" class="fa fa-sign-out"></ a>`)
        $('.user-info .text h3').html(`昵称 ${user}<span><b>个性宣言</b>:${res.data.userInfo.notes ? res.data.userInfo.notes : '走自己的路，让人说去吧'}</span>`)
      }
    })

  }

  // 点击退出登录
  $('.slinks').on('click', '.fa', function () {
    location.href = './login.html'
    localStorage.removeItem('token')
  })




})